//
//  PayManager.m
//  PigMarket
//
//  Created by mac on 2019/5/17.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "PayManager.h"
#import <AlipaySDK/AlipaySDK.h>


// 支付宝scheme
#define kFORM_SCHEME @"com.naturalgrowth.pigmarket.customer"
// 微信appid
#define kWX_APPID @"wx97793237fbc3485a"
// 回调url地址为空
#define KCALLBACKURL @"url地址不能为空！"
// 订单信息为空字符串或者nil
#define KORDERMESSAGE @"订单信息不能为空！"
// 没添加 URL Types
#define KURLTYPE @"请先在Info.plist 添加 URL Type"
// 添加了 URL Types 但信息不全
#define KURLTYPE_SCHEME(name) [NSString stringWithFormat:@"请先在Info.plist 的 URL Type 添加 %@ 对应的 URL Scheme",name]
@interface PayManager ()<WXApiDelegate>
/**
 callBack
 */
@property (nonatomic , strong) PayCompleteCallBack payCompleteCallBack;
@end

@implementation PayManager

#pragma mark - 单例
+(instancetype)sharedManager {
    static dispatch_once_t onceToken;
    static PayManager *instance;
    dispatch_once(&onceToken, ^{
        instance = [[PayManager alloc] init];
        
    });
    return instance;
    
}
#pragma mark - 微信注册
- (void)wxPayRegister {
    //plist文件读取数值
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"CommonConfig" ofType:@"plist"];
//    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
//
    //向微信注册,发起支付必须注册
    [WXApi registerApp:kWX_APPID enableMTA:YES];
}
#pragma mark - 处理跳转回调
- (BOOL)handelPayURL:(NSURL *)url {
    NSAssert(url, KCALLBACKURL);
    if ([url.host isEqualToString:@"pay"]) {
        
        return [WXApi handleOpenURL:url delegate:self];
    } else if ([url.host isEqualToString:@"safepay"]){
        
        // 支付跳转支付宝钱包进行支付，处理支付结果(在app被杀模式下，通过这个方法获取支付结果）
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSString *resultSatus = resultDic[@"resultStatus"];
            NSString *errStr = resultDic[@"memo"];
            PayErrCode errorCode = PayErrCodeSuccess;
            switch ([resultSatus intValue]) {
                case 9000:
                    errorCode = PayErrCodeSuccess;
                    break;
                case 6001:
                    errorCode = PayErrCodeCancel;
                    break;
                default:
                    errorCode = PayErrCodeFailure;
                    
                    break;
            }
            if ([PayManager sharedManager].payCompleteCallBack) {
                [PayManager sharedManager].payCompleteCallBack(errorCode,errStr);
            }
        }];
        //授权跳转支付宝进行支付,处理支付结果
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
        return YES;
    } else {
        return NO;
    }
}
#pragma mark - 微信支付
- (void)payWithWeChatMethod:(Pay *)model callBack:(PayCompleteCallBack)callBack{
    self.payCompleteCallBack = callBack;

    if (![WXApi isWXAppInstalled]) {//是否已经安装微信app
        [[AlertAction sharedInstance] showAlertWithTitle:nil message:@"未安装微信，请选择其他支付方式" confirmBtnTitle:@"确定" confirmBlock:nil cancelBlock:nil];
        return;
    }
    PayReq *req = [[PayReq alloc] init];
    req.partnerId = model.partnerid;
    req.prepayId = model.prepayid;
    req.nonceStr = model.noncestr;
    req.timeStamp = [model.timestamp intValue];
    req.package = model.package;
    req.sign = model.sign;
    [WXApi sendReq:req];
}
#pragma mark - WXApiDelegate
//收到微信回调
- (void)onResp:(BaseResp *)resp {
    if([resp isKindOfClass:[PayResp class]]){
        //支付回调
        PayErrCode errorCode = PayErrCodeSuccess;
        NSString *errStr = resp.errStr;
        switch (resp.errCode) {
            case 0:
                errorCode = PayErrCodeSuccess;
                errStr = @"订单支付成功";
                break;
            case -1:
                errorCode = PayErrCodeFailure;
                errStr = resp.errStr;
                break;
            case -2:
                errorCode = PayErrCodeCancel;
                errStr = @"用户中途取消";
                break;
            default:
                errorCode = PayErrCodeFailure;
                errStr = resp.errStr;
                break;
        }
        if (self.payCompleteCallBack) {
            self.payCompleteCallBack(errorCode,errStr);
        }
    }
}
#pragma mark - 支付宝支付
- (void)payWithAlipayMethod:(NSString *)payOrder callBack:(PayCompleteCallBack)callBack {
    self.payCompleteCallBack = callBack;

    [[AlipaySDK defaultService] payOrder:payOrder fromScheme:kFORM_SCHEME callback:^(NSDictionary *resultDic) {
       
        PMLog(@"支付回调%@",resultDic);
        
         //注，网页回调不会走AppDelegate代理方法。只能通过这里来处理回调
        NSString *resultStatus = resultDic[@"resultStatus"];
        NSString *errStr = resultDic[@"memo"];
        PayErrCode errorCode = PayErrCodeSuccess;
        switch (resultStatus.integerValue) {
            case 9000:// 成功
                errorCode = PayErrCodeSuccess;
                break;
            case 6001:// 取消
                errorCode = PayErrCodeCancel;
                break;
            default:
                errorCode = PayErrCodeFailure;
                break;
        }
        if ([PayManager sharedManager].payCompleteCallBack) {
            [PayManager sharedManager].payCompleteCallBack(errorCode,errStr);
        }
    }];
}


@end
